from django.db.models import F

from chat.models import AtMessage
from forum.models import Comment, CommentThumb, BoardTopic
from user_app.models import AccountInfo
from utils import wx_method, query_utils
from utils.common_utils import json_response, Pagination, AccountManager
from utils.decorators import json_check, check_login
from django.conf import settings

_CATEGORY = 2


@check_login
@json_check
def post_comment(request, json_data: dict):
    account_id = request.session['account_id']
    topic_id = json_data.get('board_id')
    content = json_data.get('content')
    parent_id = json_data.get('parent_id')
    reply_account_id = json_data.get('reply_account_id')
    flag, tc = __check_board(topic_id)
    if not flag:
        return json_response({"code": 1000, "message": "帖子不存在"})
    flag, msg = query_utils.check_allow_post(account_id)
    if flag:
        return json_response({"code": 1000, "message": msg})
    is_mobile = json_data.get("is_mobile", False)
    if is_mobile:
        # 小程序端需要文本内容合法性校验
        code, message = wx_method.wx_check_content(content)
        if code != 0:
            return json_response({"code": code, "message": message})
    cm = Comment()
    cm.topic_id = topic_id
    cm.content = content
    cm.category = _CATEGORY
    cm.created_by_id = account_id
    if parent_id:
        cm.parent_id = parent_id
    if reply_account_id:
        cm.reply_account_id = reply_account_id
    cm.save()
    cm.refresh_from_db()
    # topic评论数+1
    topic = tc[0]
    topic.last_post_account_id = AccountInfo.objects.get(id=account_id)
    topic.num_replies = F('num_replies') + 1
    topic.save(update_fields=['num_replies', 'last_post_account_id'])
    result_dict = {

    }
    # # 新增@消息的提醒
    # if reply_account_id:
    #     at_message = AtMessage()
    #     at_message.comment_id = cm.id
    #     at_message.receive_id = cm.reply_account_id
    #     at_message.created_by_id = account_id
    #     at_message.save()
    return json_response({"code": 0, "message": "评论成功", "data": result_dict})


#@check_login
def get_comment_list(request):
    account_id = request.session.get('account_id', '')

    topic_id = request.GET.get('board_id')
    if not topic_id:
        return json_response({"code": 1000, "message": "帖子参数错误"})
    page = int(request.GET.get('page', "1"))
    per_page = int(request.GET.get("per_page", "10"))
    comment_count = Comment.objects.filter(topic_id=topic_id, parent_id=0, category=_CATEGORY).count()
    p = Pagination(page=page, per_page=per_page, total=comment_count)
    comment_list = Comment.objects.filter(topic_id=topic_id, parent_id=0, category=_CATEGORY).order_by("-created_on")[p.offset:p.offset + per_page]
    result_list = []
    account_mg = AccountManager()
    for item in comment_list:
        created_by_id = item.created_by_id
        account_info = account_mg.get_account_by_id(created_by_id)
        reply_account_id = item.reply_account_id
        tmp = {
            "id": item.id,
            "topic_id": item.topic_id,
            "content": item.content,
            "numthumb": item.num_thumb,
            "nick_name": account_info.nick_name,
            "avatar": account_info.avatar,
            "created_account_id": created_by_id,
            "created_time": item.created_on,
            "reply_account_id": reply_account_id if reply_account_id else "",
            "reply_account_name": account_mg.get_account_by_id(reply_account_id).nick_name if reply_account_id else "",
            "isthumb": CommentThumb.objects.filter(comment_id=item.id, created_by_id=account_id, category=_CATEGORY).exists() if account_id else False,
        }
        if Comment.objects.filter(parent_id=item.id, category=_CATEGORY).exists():
            tmp['children'] = __get_children_comment(item.id, account_mg, account_id)
        result_list.append(tmp)
    return json_response({"code": 0, "message": "", "data": {"item": result_list, "page_info": p.dict}})


@check_login
def comment_thumb(request):
    # 给帖子点赞/取消赞接口
    account_id = request.session['account_id']
    comment_id = request.GET.get('comment_id')
    cm = Comment.objects.filter(id=comment_id, category=_CATEGORY)
    if not cm:
        return json_response({"code": 1000, "message": "评论不存在"})
    thumb = CommentThumb.objects.filter(created_by_id=account_id, comment_id=comment_id, category=_CATEGORY)
    result_dict = {

    }
    comment = cm[0]
    if thumb:
        thumb.delete()
        result_dict['flag'] = False

        comment.num_thumb = F('num_thumb') - 1
        comment.save(update_fields=['num_thumb'])
        return json_response({"code": 0, "message": "取消点赞", "data": result_dict})
    else:
        tb = CommentThumb()
        tb.comment_id = comment_id
        tb.comment_account_id = cm[0].created_by_id
        tb.created_by_id = account_id
        tb.category = _CATEGORY
        tb.save()
        result_dict['flag'] = True
        comment.num_thumb = F('num_thumb') + 1
        comment.save(update_fields=['num_thumb'])
        return json_response({"code": 0, "message": "点赞成功", "data": result_dict})


def __check_board(topic_id):
    tc = BoardTopic.objects.filter(id=topic_id)
    if not tc:
        return False, tc
    return True, tc


def __get_children_comment(parent_id, account_mg, account_id):
    # 获取子级评论
    children_comment = Comment.objects.filter(parent_id=parent_id, category=_CATEGORY)
    children_list = []
    for child in children_comment:
        created_by_id = child.created_by_id
        account_info = account_mg.get_account_by_id(created_by_id)
        reply_account_id = child.reply_account_id
        tmp = {
            "id": child.id,
            "topic_id": child.topic_id,
            "content": child.content,
            "numthumb": child.num_thumb,
            "nick_name": account_info.nick_name,
            "avatar": account_info.avatar,
            "created_account_id": child.created_by_id,
            "created_time": child.created_on,
            "reply_account_id": reply_account_id if reply_account_id else "",
            "reply_account_name": account_mg.get_account_by_id(reply_account_id).nick_name if reply_account_id else "",
            "isthumb": CommentThumb.objects.filter(comment_id=child.id, created_by_id=account_id, category=_CATEGORY).exists() if account_id else False,
        }
        children_list.append(tmp)
    return children_list
